package com.bridgeintelligent.tag.webserver.dim.mgmt.service.dimfree;

import com.bridgeintelligent.tag.annotations.Resubmit;
import com.bridgeintelligent.tag.utils.PasswordHelper;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.BaseCode;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.DepartmentRep;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.DimRep;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.IdWorker;
import com.bridgeintelligent.tag.webserver.dim.mgmt.service.catalog.model.DimFreeModel;
import com.bridgeintelligent.tag.webserver.dim.mgmt.service.catalog.model.DimListModel;
import com.bridgeintelligent.tag.webserver.dim.mgmt.service.scheduled.DepartmentApi;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by JackCheung on 2019/9/12 2:04 PM.
 */
@Slf4j
@Api(tags = "自定义标签管理")
@RestController
@RequestMapping("/api/dimFree")
public class DimFreeController {

    @Autowired
    private IDimFreeService dimFreeService;
    private static String CSV_TYPE = "csv";
    private static String TXT_TYPE = "txt";

    @ApiOperation(value = "新增自定义标签", notes = "自定义标签管理")
    @PostMapping("add")
    public DimRep add(@ModelAttribute DimFreeModel dimFreeModel, @ApiParam(value = "客户名单文件") MultipartFile multipartFile) {
        if (PasswordHelper.checkSpecial(dimFreeModel.getDimName())){
            return new DimRep(-1, "名字含有特殊字符");
        }
        return dimFreeService.add(dimFreeModel, multipartFile);
    }

    @ApiOperation(value = "获取自定义标签列表", notes = "自定义标签管理")
    @GetMapping("list")
    public DimRep list(@ModelAttribute DimListModel dimListModel) {
        checkDim(dimListModel);
        return dimFreeService.list(dimListModel);
    }

    @ApiOperation(value = "新增-获取id", notes = "自定义标签管理")
    @GetMapping("getId")
    public DimRep getId() {
        return new DimRep<>(IdWorker.nextId(), BaseCode.SUCCESS);
    }

    @ApiOperation(value = "新增-上传文件", notes = "自定义标签管理")
    @PostMapping("up")
    public DimRep up(String id, boolean ecifFlag,
                    @ApiParam(value = "客户名单文件") MultipartFile multipartFile) {
        return dimFreeService.up(id, ecifFlag, multipartFile);
    }

    @ApiOperation(value = "新增-新建", notes = "自定义标签管理")
    @PostMapping("addById")
    @Resubmit
    public DimRep addById(@ModelAttribute DimFreeModel dimFreeModel) {
        return dimFreeService.addById(dimFreeModel);
    }

    @ApiOperation(value = "查看自定义标签详情", notes = "自定义标签管理")
    @GetMapping("detail")
    public DimRep detail(String dimId) {
        return dimFreeService.detail(dimId);
    }

    @ApiOperation(value = "清理自定义标签", notes = "自定义标签管理")
    @GetMapping("clear")
    public DimRep clear(String dimId) {
        return dimFreeService.clear(dimId);
    }

    @ApiOperation(value = "删除自定义标签", notes = "自定义标签管理")
    @PostMapping("del")
    public DimRep del(String dimId) {
        return dimFreeService.del(dimId);
    }

    @ApiOperation(value = "获取已删除的自定义标签", notes = "自定义标签管理")
    @GetMapping("delList")
    public DimRep delList(@ModelAttribute DimListModel dimListModel) {
        checkDim(dimListModel);
        return dimFreeService.delList(dimListModel);
    }

    @ApiOperation(value = "修改自定义标签信息基础信息", notes = "自定义标签管理")
    @PostMapping("updateBaseInfo")
    public DimRep updateBaseInfo(@ModelAttribute DimFreeModel dimFreeModel) {
        if (PasswordHelper.checkSpecial(dimFreeModel.getDimName())){
            return new DimRep(-1, "名字含有特殊字符");
        }
        return dimFreeService.updateBaseInfo(dimFreeModel);
    }

    @ApiOperation(value = "增加自定义标签用户列表", notes = "自定义标签管理")
    @PostMapping("addCusts")
    public DimRep addCusts(String dimId, @ApiParam(value = "客户名单文件") MultipartFile multipartFile, String fileDescription) {

        return dimFreeService.addCusts(dimId, multipartFile, fileDescription);
    }

    @ApiOperation(value = "删除自定义标签用户列表", notes = "自定义标签管理")
    @PostMapping("delCusts")
    public DimRep delCusts(String dimId, @ApiParam(value = "客户名单文件") MultipartFile multipartFile, String fileDescription) {
        if (!multipartFile.getOriginalFilename()
                          .contains(TXT_TYPE)) {
            return new DimRep(999, "文件必须是txt类型！");
        }
        return dimFreeService.delCusts(dimId, multipartFile, fileDescription);
    }

    /**
     * 下载客群文件
     *
     * @return
     */
    @ApiOperation("下载定制标签文件")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "id", value = "定制标签id")})
    @GetMapping("/downLoad")
    public void downLoad(String id, HttpServletResponse response,HttpServletRequest req) {
        dimFreeService.downLoad(id, response,req);
    }

    /**
     * 下载客群文件
     *
     * @return
     */
    @ApiOperation("下载定制标签校验文件")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "id", value = "定制标签id")})
    @GetMapping("/downLoadError")
    public void downLoadError(String id, HttpServletResponse response,HttpServletRequest req) {
        dimFreeService.downLoadError(id, response,req);
    }

    private void checkDim(DimListModel dimListModel) {
        dimListModel.setPageNumber(dimListModel.getPageNumber() == null ? 1 : dimListModel.getPageNumber());
        dimListModel.setPageSize(dimListModel.getPageSize() == null ? 10 : dimListModel.getPageSize());
        if (StringUtils.isNotEmpty(dimListModel.getCreateTimeStart())) {
            dimListModel.setCreateTimeStart(dimListModel.getCreateTimeStart() + " 00:00:00");
        }
        if (StringUtils.isNotEmpty(dimListModel.getCreateTimeEnd())) {
            dimListModel.setCreateTimeEnd(dimListModel.getCreateTimeEnd() + " 23:59:59");
        }
        if (StringUtils.isNotEmpty(dimListModel.getUptTimeStart())) {
            dimListModel.setUptTimeStart(dimListModel.getUptTimeStart() + " 00:00:00");
        }
        if (StringUtils.isNotEmpty(dimListModel.getUptTimeEnd())) {
            dimListModel.setUptTimeEnd(dimListModel.getUptTimeEnd() + " 23:59:59");
        }
    }

    public static boolean checkSuffix(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        return "csv".equals(suffix);
    }

    /**
     * 定制标签备份历史文件ToHDFS以及补发失败文件
     *
     * @return
     */
    @ApiOperation("定制标签备份历史文件以及补发失败文件")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "type", value = "补发类型：history（历史所有）｜error（上传失败的）｜singal（指定文件）｜period（指定时间段内，此时startDate和endDate需要传值）"),
            @ApiImplicitParam(paramType = "query", name = "dimId", value = "指定定制标签的ID"),
            @ApiImplicitParam(paramType = "query", name = "startDate", value = "某个时间段内的开始时间,格式yyyy-mm-dd hh:mm:ss"),
            @ApiImplicitParam(paramType = "query", name = "endDate", value = "某个时间段内的结束时间,格式yyyy-mm-dd hh:mm:ss"),
    })
    @GetMapping("/historyFileBakup")
    public DimRep historyFileBakup(String type,String dimId,String startDate,String endDate) {
        try{
            return new DimRep(dimFreeService.doFileBakup(type,dimId,startDate,endDate),BaseCode.SUCCESS);
        }catch(Exception e){
            return new DimRep(e.getMessage(),BaseCode.FAIL);
        }
    }

}
